//
//  XHF_SMSLoginViewController.m
//  haojia
//
//  Created by 徐宏飞 on 16/5/18.
//  Copyright © 2016年 徐宏飞. All rights reserved.
//

#import "XHF_SMSLoginViewController.h"
#import "XHF_LoginViewController.h"
#import "XHF_RegSeccodeViewController.h" //注册

@interface XHF_SMSLoginViewController ()<XHF_LoginViewControllerDelegate,NetworkToolerDelegate, UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *tfdPhoneNum;
@property (weak, nonatomic) IBOutlet UITextField *tfdSmsCode;
@property (weak, nonatomic) IBOutlet UIButton *btnLogin;
@property (weak, nonatomic) IBOutlet UIButton *btnReg;


@property (strong, nonatomic) UIView *imgPhoneNum;
@property (strong, nonatomic) UIView *imgSmsCode;
@property (weak, nonatomic) IBOutlet UIButton *rightBtn;  //验证码

@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSInteger timeNumber;

@property (nonatomic, copy) NSString *sms;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollV;

@property (weak, nonatomic) IBOutlet UIView *baseView;


@property (nonatomic, strong) UITapGestureRecognizer *tap;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *imgIconTop;


@property (strong, nonatomic)NetworkTooler *networkTool;
@end

@implementation XHF_SMSLoginViewController



#pragma mark - life cycle
- (void)initNavigationBar
{
    self.enableReturnButton = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"验证码登录";
    self.view.backgroundColor = UIColorFromRGB(0xFAFAFA);
    self.scrollV.scrollEnabled = NO;
    _networkTool = [NetworkTooler new];

    
    
    //手机号
    self.tfdPhoneNum.leftView = self.imgPhoneNum;
    self.tfdPhoneNum.leftViewMode = UITextFieldViewModeAlways;
    
    //密码
    self.tfdSmsCode.leftView = self.imgSmsCode;
    self.tfdSmsCode.leftViewMode = UITextFieldViewModeAlways;
    
//    self.tfdSmsCode.rightView = self.rightBtn;
//    self.tfdSmsCode.rightViewMode = UITextFieldViewModeAlways;
    
    [_baseView addGestureRecognizer:self.tap];
    
    
    UIButton *retButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [retButton setImage:FW_IMAGE(@"loginback") forState:UIControlStateNormal];
    retButton.frame = CGRectMake(-5, 0, 24, 24);
    if (!FW_IOS7) {
        retButton.frame = CGRectMake(0, 0, kBorder_NavButton, kBorder_NavButton);
    }
    //    setButton.backgroundColor = [UIColor redColor];
    [retButton addTarget:self action:@selector(retButtonAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *retItem = [[UIBarButtonItem alloc] initWithCustomView:retButton];
    self.navigationItem.leftBarButtonItem = retItem;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    
    
    //右
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 60, 20);
    [btn setTitle:@"密码登录" forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:14];
    [btn setTitleColor:WHITE forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(pushToLoginViewController) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIBarButtonItem *barBtn = [[UIBarButtonItem alloc] initWithCustomView:btn];
    
    self.navigationItem.rightBarButtonItem = barBtn;
    
    if ( self.tfdPhoneNum) {

        [self _username];
    }
    
    
    if (SCREEN_HEIGHT == 480 || SCREEN_HEIGHT ==568) {
        self.imgIconTop.constant = 20;
    }
    
    
    
    
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    //初始化计时器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(trackAction) userInfo:nil repeats:YES];
    [self.timer setFireDate:[NSDate distantFuture]]; //关闭
    
    
    //监听键盘的弹出事件
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
}


- (void)viewDidDisappear:(BOOL)animated{
    //移除监听
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


#pragma mark - data

-(void) _testRequst{
    
    
    NSDictionary *parameters = @{
                                 
                                 @"mobile":self.tfdPhoneNum.text,
                                 @"type":@4
                                 
                                 };
    
    
    
     _networkTool.delegate = self;
    [_networkTool parameters:parameters withURL:GetMsgCode_show withIsPaparameters:YES];
    
}


-(void) _SMSLoginRequst{
    
    
    NSDictionary *parameters = @{
                                 
                                 @"mobile":self.tfdPhoneNum.text,
                                 @"msg_code":self.tfdSmsCode.text
                                 
                                 };
  
    _networkTool.delegate = self;

    [_networkTool parameters:parameters withURL:SmsLogin_show withIsPaparameters:YES];
    
    
}



#pragma mark - NetworkToolerDelegate

- (void)returnData:(id)data{
    

    
    if (isNSDictionary) {
        
        
        NSString *sessionid = [data objectForKey:@"session_id"];
        NSString *worker_id = [data objectForKey:@"worker_id"];
        
        [MobClick profileSignInWithPUID:self.tfdPhoneNum.text];

        Locatianmanager *locationmanager = [Locatianmanager shareManager];
        [locationmanager startLocation];
        //将数据写入本地
        
        NSDictionary *loginData = [NSDictionary dictionaryWithObjectsAndKeys:
                                   sessionid, @"sessionid",
                                   worker_id,@"worker_id",
                                   @"1", @"loginSucceed",
                                   nil];
        
        
        
        [[NSUserDefaults standardUserDefaults] setObject:self.tfdPhoneNum.text forKey:@"mobile"];
        
        [[NSUserDefaults standardUserDefaults] setObject:loginData forKey:@"loginData"];
        //同步数据
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        
        //返回
        switch (self.logintype) {
            case LOGINTYPEME:
                
                [self.navigationController popViewControllerAnimated:NO];
                
                break;
            case LOGINTYPEOTERS:
                
                [self dismissViewControllerAnimated:YES completion:nil];
                
                break;
                
            default:
                break;
        }
        
    }
    
    
}
- (void)returnRequestError:(NSError *)error{
    
    
}

- (void)returnMsg:(NSString *)Msg{
    
    
    [self showAlertWithTitle:@"温馨提示" message:Msg cancelButtonTitle:@"取消" otherButtonTitles:@"确定"];
    
    if ([Msg isEqualToString:@"该手机号未注册"]) {
        [self.timer setFireDate:[NSDate distantFuture]]; //关闭
        _rightBtn.enabled = YES;
    }

}





-(void) _username{
    ZhuangxiuManager *manager = [ZhuangxiuManager shareManager];
    if (manager.mobile != nil) {
        self.tfdPhoneNum.text = manager.mobile;
    }
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.view endEditing:YES];
    return YES;
}





#pragma mark - event response

- (void)popTorootVC{
    
    //返回
    switch (self.logintype) {
        case LOGINTYPEME:
            
            [self.navigationController popViewControllerAnimated:YES];
            break;
        case LOGINTYPEOTERS:
            
            [self dismissViewControllerAnimated:YES completion:nil];
            
            break;
            
        default:
            break;
    }
}
- (IBAction)UserArotocolAction:(id)sender {
    XHF_WebViewController *webVC = [XHF_WebViewController new];
    webVC.title = @"用户协议";
    webVC.url = @"http://www.youku.com";
    webVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:webVC animated:YES];
}


- (void)TapAction{
    [self.view endEditing:YES];
}

- (void)retButtonAction{
    //返回
    switch (self.logintype) {
        case LOGINTYPEME:
            
            [self.navigationController popViewControllerAnimated:YES];
            break;
        case LOGINTYPEOTERS:
            
            [self dismissViewControllerAnimated:YES completion:nil];
            
            break;
            
        default:
            break;
    }
    
}
- (void)pushToLoginViewController{
    
    XHF_LoginViewController *login = [XHF_LoginViewController new];
    login.delegate = self;
    
    [self.navigationController pushViewController:login animated:YES];
    
}

- (void)keyboardWillChangeFrame:(NSNotification *)notification{
    //获取键盘的Y值
    CGRect rect = [[notification.userInfo objectForKey:@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
    CGFloat keybordY = rect.origin.y;
    CGFloat tranformValue = keybordY - self.view.frame.size.height;
    CGFloat value = 0;
    CGPoint point = CGPointMake(0, -tranformValue*value);
    
    
    if (SCREEN_HEIGHT == 736) {
        value = 0.3;
        point = CGPointMake(0, -tranformValue*value);
        _scrollV.contentOffset = point;
        if (point.y <= 0) {
            _scrollV.contentOffset = CGPointMake(0, 0);
        }
    }
    
    
    if (SCREEN_HEIGHT == 667) {  //6s
        value = 0.6;
        point = CGPointMake(0, -tranformValue*value);
        _scrollV.contentOffset = point;
        if (point.y <= 0) {
            _scrollV.contentOffset = CGPointMake(0, 0);
        }
    }
    
    if (SCREEN_HEIGHT == 568) {  //5 5s
        value = 0.6;
        point = CGPointMake(0, -tranformValue*value);
        _scrollV.contentOffset = point;
        if (point.y <= 0) {
            _scrollV.contentOffset = CGPointMake(0, 0);
        }
    }
    
    if (SCREEN_HEIGHT == 480) {  // 4s
        value = 0.9;
        point = CGPointMake(0, -tranformValue*value);
        _scrollV.contentOffset = point;
        if (point.y <= 0) {
            _scrollV.contentOffset = CGPointMake(0, 0);
        }
    }
   
}



- (IBAction)loginAction:(id)sender {
    //过滤登录条件
    //过滤登录条件
    if ([self.tfdPhoneNum.text isEqualToString:@""]) {
        [self showAlertWithTitle:@"温馨提示"message:@"账户不能为空" cancelButtonTitle:@"取消" otherButtonTitles:@"确定"];
        return;
    }
    if ([self.tfdSmsCode.text isEqualToString:@""]) {
        [self showAlertWithTitle:@"温馨提示" message:@"验证码不能为空" cancelButtonTitle:@"取消" otherButtonTitles:@"确定"];
        return;
    }
    
    
    
    [self _SMSLoginRequst];
    //登录按钮
}

- (IBAction)regAction:(id)sender {
    //进入注册密码
    XHF_RegSeccodeViewController *reg = [XHF_RegSeccodeViewController new];
    reg.title = @"账号注册";
    reg.smsType = SMSTYP_WORK_REGISTRT;
    [self.navigationController pushViewController:reg animated:YES];
    
    
}




- (void)trackAction{
    _timeNumber ++;
    [_rightBtn setTitle:[NSString stringWithFormat:@"%ld", 10 - _timeNumber] forState:UIControlStateDisabled];
    if (_timeNumber >= 10) {
        [self.timer setFireDate:[NSDate distantFuture]]; //关闭
        _rightBtn.enabled = YES;
        
    }
    
    
}


- (IBAction)rightBtnClick:(id)sender {
    //过滤登录条件
    if ([self.tfdPhoneNum.text isEqualToString:@""]) {
        [self showAlertWithTitle:@"温馨提示" message:@"手机号不能为空" cancelButtonTitle:@"取消" otherButtonTitles:@"确定"];
        return;
    }
    
    if (![self PhoneNumIsvalid:self.tfdPhoneNum.text]) {
        [self showAlertWithTitle:@"温馨提示" message:@"手机号码不合法" cancelButtonTitle:@"取消" otherButtonTitles:@"确定"];
        return;
    }
    
    //倒计时
    _rightBtn.enabled = NO;
    _timeNumber = 0;
    [self.timer setFireDate:[NSDate distantPast]];   //开启
    
    //获取验证码
    [self _testRequst];
}




#pragma mark - gettsers and setters

- (UIView *)imgPhoneNum{
    if (!_imgPhoneNum) {
        _imgPhoneNum = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"userIcon"]];
        _imgPhoneNum.frame = CGRectMake(0, 0, 20, 20);
    }
    return _imgPhoneNum;
}

- (UIView *)imgSmsCode{
    if (!_imgSmsCode) {
        _imgSmsCode = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pwdIcon"]];
        _imgSmsCode.frame = CGRectMake(0, 0, 20, 20);
    }
    return _imgSmsCode;
}




- (UITapGestureRecognizer *)tap{
    if (!_tap) {
        _tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(TapAction)];
    }
    
    return _tap;
}


@end
